/**
 * 
 */
package wong.board.client.ui;

import java.util.logging.Logger;

import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.IsWidget;

/**
 * @author wong
 * 
 */
public abstract class Presenter<PresenterView extends Presenter.View, PresenterValue> {
	protected static final Logger logger = Logger.getLogger(Presenter.class.getName());
	private final PresenterView view;
	private UIHandler handler;

	public Presenter(PresenterView view) {
		assert view != null : "view must not be null";
		this.view = view;
	}

	public PresenterView getView() {
		if (handler == null) {
			handler = new UIHandler();
		}
		return view;
	}

	public void flush() {
		if (handler != null) {
			handler.flush();
			handler = null;
		}
	}

	protected void onViewAttached() {
	}

	protected void onViewDetached() {
	}

	public abstract void updateView(PresenterValue value);

	/*
	 * 
	 */

	private class UIHandler implements Handler {

		private HandlerRegistration attachRegistration;

		public UIHandler() {
			attachRegistration = Presenter.this.view.asWidget().addAttachHandler(this);
			if (Presenter.this.view.asWidget().isAttached()) {
				onViewAttached();
			}
		}

		public void flush() {
			attachRegistration.removeHandler();
			attachRegistration = null;
		}

		@Override
		public void onAttachOrDetach(AttachEvent event) {
			if (event.isAttached()) {
				onViewAttached();
			} else {
				onViewDetached();
			}
		}

	}

	public interface View extends IsWidget {

	}

}
